/* a simplified version of pwd */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>

ino_t get_inode(char *);
void printpathto(ino_t);
void inum_to_name(ino_t, char *, int);

int main(){
	ino_t cur_inode = get_inode(".");
	// 根目录：当前目录.和上一层目录.. 指向同一个inode
	if (get_inode("..") == cur_inode){
		printf("/");
	}else{
		// 打印从根目录到当前目录的路径
		printpathto(cur_inode);
	}
	putchar('\n');
	return 0;
}

/* recursively execute this function to print path */
void printpathto(ino_t this_inode){
	ino_t my_inode;
	char its_name[BUFSIZ];
	//recursive function stop rule: the inodes of "." and ".." are the same */
	if (get_inode("..") != this_inode){
		// 到上一层
		chdir("..");
		inum_to_name(this_inode,its_name,BUFSIZ);
		my_inode = get_inode(".");
		printpathto(my_inode);
		// 递归的执行，则从根目录开始打印
		printf("/%s", its_name);
	}
}

/* check all inodes in current directory to find a file
 * with a matched inode with inode_to_find
 */
void inum_to_name(ino_t inode_to_find, char *namebuf, int buflen){
	DIR * dir_ptr;
	struct dirent * direntp;
	// 得到当前目录的指针，可以使用该指针来遍历当前目录下的所有目录和文件
	dir_ptr = opendir(".");
	if (dir_ptr == NULL){
		perror(".");
		exit(1);
	}
	//search directory
	while ((direntp = readdir(dir_ptr)) != NULL){
		if (direntp->d_ino == inode_to_find){
			strncpy(namebuf, direntp->d_name, buflen);
			namebuf[buflen - 1] = '\0';
			closedir(dir_ptr);
			return;
		}
	}
	fprintf(stderr, "error looking for inum %lu\n", inode_to_find);
	exit(1);
}

/* return the inode number of the given file *fname */
ino_t get_inode(char * fname){
	struct stat info;
	if (stat(fname, &info) == -1){
		fprintf(stderr, "Cannot stat");
		perror(fname);
		exit(1);
	}
	return info.st_ino;
}
